package org.datamining.guha.model;

import java.util.List;

import org.datamining.guha.model.literal.Literal;
import org.datamining.guha.model.node.Node;
import org.datamining.guha.model.node.NodeFactory;

public class LiteralSourceRowImpl implements LiteralSourceRow {
	
	private NodeFactory nodeFactory;
    private List<Literal> row;
    private Formatter<LiteralSourceRow> formatter;
    
    /** Creates a new instance of LiteralSourceRow */
    public LiteralSourceRowImpl(List<Literal> literal) {
        this.row = literal;
        this.formatter = new Formatter<LiteralSourceRow>() {
			public String format(LiteralSourceRow object) {
				StringBuffer sb = new StringBuffer();
		        for (int i = 0; i < row.size(); i++) {
		            Literal lit = row.get(i);
		            sb.append(lit + " ");
		        }
		        return sb.toString();
			}
        };
    }
    
    public List<Literal> getSourceLiterals() {
        return this.row;
    }

    public Node getTreeOrderedAccordingTo(FrequencyOrderedList frList) {
        Node tree = null;
        List<Literal> list = frList.getLiteralList();
        
        // It is important to return correct order
        // we can't loop in 'i > 0' !!!
        
        int size = list.size();
        for(int i = 0; i < size; i++) {
            Literal lit = list.get(i);
            if (row.contains(lit)) {
                //int index = row.indexOf(lit);
            	Node newNode = nodeFactory.getNode(lit, null, null, 1);
                if (tree == null) {
                    // create first Node
                    tree = newNode;
                } else {
                    // get last node in line.
                    //Node lastNode = null;
                    Node currentNode = tree;
                    while (currentNode.getSuccessors().size() != 0 ) {
                        // get first successor
                        //currentNode = currentNode.getSuccessor(0);
                    	currentNode = currentNode.getSuccessors().getFirst();
                    }
                    // append new Node(Literal) to last node in tree
                    currentNode.getSuccessors().add(newNode);
                    // and set parent to the last node.
                    newNode.setParent(currentNode);
                }
            }
        }
        return tree;
    }

    public String toString() {
    	if (formatter == null) throw new RuntimeException("Formatter must be set first");
    	return formatter.format(this);
    }

	public void setNodeFactory(NodeFactory nodeProvider) {
		this.nodeFactory = nodeProvider;
	}
	
	public NodeFactory getNodeFactory() {
		return nodeFactory;
	}

	public Formatter<LiteralSourceRow> getFormatter() {
		return formatter;
	}

	public void setFormatter(Formatter<LiteralSourceRow> formatter) {
		this.formatter = formatter;
	}

}
